<template>
	<view class="wx-auth">
		<view class="wx-auth" v-if="isCanUse">
			<view class="header"><image src="https://web.suqzp.com/public/head.png"></image></view>
			<view class="content2">
				<view class="text-size-max">申请获取以下权限</view>
				<text>获得您的公开信息(昵称，头像等)</text>
			</view>
			<view class="bottom">
				<button class="cancel-login" type="default" lang="zh_CN" @click="cancle()">暂不登录</button>
				<button size="default" class="auth" @tap="getUserProfile">授权登录</button>
			</view>
			<!-- <button hover-class="none" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权手机号</button>	 -->
			<view class="text-tc">登录代表您已同意
				<text class="fc-52c" @click="toAgree(1)">《用户协议》、</text>
				<text class="fc-52c" @click="toAgree(2)">《隐私政策》</text>
			</view>		
		</view>
		<view v-if="isCanUse2">
			<view>
				<view class='header'>
					<image :src='avatar'></image>
				</view>
				<view class='content2'>
					<view>申请获取以下权限</view>
					<text>第二步：获得你的手机号用于绑定登录</text>
				</view>
				<view class="bottom">
					<button hover-class="none" open-type="getPhoneNumber" class="auth" @getphonenumber="getPhoneNumber">授权手机号</button>
				</view>
				
			</view>
		</view>
		<view v-else>请升级微信版本</view>
	</view>
</template>

<script>
	
import { setTokenStorage } from '../../utils/token';
import logger from '../../utils/logger';
import { genTestUserSig } from '../../debug/GenerateTestUserSig.js';
const { getTokenStorage } = require('../../utils/token.js');
const app = getApp();

export default {
	data() {
		return {
			//判断小程序的API，回调，参数，组件等是否在当前版本可用。
			canIUse: uni.canIUse('button.open-type.getUserInfo'),
			bindUserInfo: null,
			code:'',
			openid:'',
			isCanUse: true, //默认为true
			isCanUse2: false, //默认为true
			avatar:'',//头像
		};
	},

	onShow: function() {
	
		
	},

	methods: {
		//获取手机号
		async getPhoneNumber (e) {
		   var code = e.detail.code		   
		   let param = {
				appid: this.$mConfig.appid,
				code: code,
				xcxOpenId: uni.getStorageSync('openid')
		   };
		   let data = await this.$apis.getPhone(param);
			uni.setStorageSync('phone', data.msg);//手机号			
			uni.navigateBack({
				delta: 1
			});
		   
		},
		async wxAuth() {
			var that = this;
			// 查看是否授权
			uni.getSetting({
				success: function(res) {
					console.log('getSetting', res);
					if (res.authSetting['scope.userInfo']) {
						uni.getUserInfo({
							success:  resData => {
								// 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
								// 根据自己的需求有其他操作再补充
								// 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
								uni.login({
									success: async res => {
										// 获取到用户的 code 之后：res.code	
										// 可以传给后台，再经过解析获取用户的 openid
										// 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
										that.code = res.code;
										// // 解密用户信息
										// let userInfo = that.getOpenId(resData);
										// 小程序登录
										that.xcxLogin()
									}
								});
							}
						});
					} else {
						// 用户没有授权
						// 改变 isHide 的值，显示授权页面
					}
				}
			});
		},

		async getOpenId(data) {
			var that = this
			let res = await this.$apis.getOpenId({appid: this.$mConfig.appid, code: that.code });
			this.openid = res.openid;
			this.session_key = res.sessionKey;
			uni.setStorageSync('openid', res.data.user.openid);//存储openid
			uni.setStorageSync('session_key', res.sessionKey);//存储session_key
			this.$store.commit('SET_OPENID', res.openid);
			uni.setStorage({
				key: 'session_key',
				data: res.sessionKey
			});
			if (res != null) {
				that.openid = res.openid				
			}
			await this.$apis.getWxInfo({appid: this.$mConfig.appid,'sessionKey':this.session_key,...data})
			// 
			await that.xcxLogin();
		},
		async xcxLogin() {
			var that = this;	
			let param = {
				appid: this.$mConfig.appid,
				code: that.code,
				token:'',
				nickname: this.bindUserInfo.nickName,
				avatar: this.bindUserInfo.avatarUrl,
				sex: this.bindUserInfo.gender,
				city: this.bindUserInfo.city
			};
			if(getApp().globalData.shareUserId){
				param['inviterUserId'] = getApp().globalData.shareUserId ||''
			}
			let res = await this.$apis.xcxUserLogin(param);
			if(!res.data){
				return
			}
			console.log(res)
			if (res.data) {
				this.$store.commit('SET_USERINFO', res.data.user || {});
				uni.setStorageSync('token', res.data.token);//存储token
				uni.setStorageSync('user', res.data.user);//存储token
				uni.setStorageSync('wxuser_id', res.data.user.id);//存储wxuser_id				
				uni.setStorageSync('isVip', res.data.user.isMember);//存储会员开通与否
				uni.setStorageSync('openid', res.data.user.openid);//存储openid
				uni.setStorageSync('isAuth', res.data.user.isAuth);//存储是否入驻	
				uni.setStorageSync('phone', res.data.phone);//存储手机号
				that.avatar =  res.data.user.avatar
				// 前端自动登录
				this.$store.commit('SET_TOKEN', res.data.token);
				console.log('即将登录im')
				
				
				await this.getUserSig(res.data.user.openid);
				await this.loginTIM(res.data.user.openid);
				/*  */
				// 更新用户信息
				// uni.redirectTo({
				// 	url:'/pages/login/authphonelogin?nickName='+this.bindUserInfo.nickName+"&avatar="+this.bindUserInfo.avatarUrl
				// })
			} 
			if(!res.data.user.phone || res.data.user.phone == ""){
				console.log('绑定手机号');
				that.isCanUse = false;
				that.isCanUse2 = true;
			}else{
				uni.navigateBack({
					delta: 1
				});
			}
		},
		async getUserSig(openid) {
			let param = {
				openid
			}
			let data = await this.$apis.getUserSig(param);
			if (data) {
				if (data.code == "200") {
					
				} else {
					uni.showToast({
						title: data.msg,
						icon: "none"
					})
				}
			}
		},
		
		getUserProfile(e) {
			var that = this;
			// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
			// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			uni.getUserProfile({
				lang:"zh_CN",
				desc: '用于完善订单用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (res) => {
					this.bindUserInfo = res.userInfo;
					this.isHide = true;
					uni.setStorageSync('isCanUse', false)			
					uni.showLoading({
						title: '授权登录中···'
					});
					this.wxAuth();
				},
				fail: (err) => {
					//用户按了拒绝按钮
					uni.showModal({
						title: '警告',
						content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
						showCancel: false,
						confirmText: '返回授权',
						success: function(res) {
							// 用户没有授权成功，不需要改变 isHide 的值
							if (res.confirm) {
								console.log('用户点击了“返回授权”');
							}
						}
					});
				}  
			})
			
		},
		cancle() {
			uni.navigateBack({
				delta: 1
			});
		},
		updateMember() {
			if (this.bindUserInfo != null) {
				var member = {
					avatar: this.bindUserInfo.avatarUrl,
					name: this.bindUserInfo.nickName,
					sex: this.bindUserInfo.gender,
					nickName: this.bindUserInfo.nickName
				};
				api.getUpdateMemberInfo(member, res => {
					if (res.data.code == 200) {
						uni.showToast({ title: res.data.message });
					}
				});
			}
		},
		//用户协议--隐私政策
		toAgree(type){
			this.$mRouter.push({
				route: this.$mRoutesConfig.agreement,
				query: {
					type:type
				}
			});
		},
		async loginTIM(openId) {
			const userID = openId;
			const userSig = genTestUserSig(userID).userSig;
			console.log(userID,2222)
			console.log(userSig,2222)
			const SDKAppID = app.globalData.SDKAppID;
			logger.log(`TUI-login | login  | userSig:${userSig} userID:${userID}`,11111111111);
			// #ifdef  APP-PLUS
			uni.$aegis.reportEvent({
			    name: 'platform',
			    ext1: 'platform-APP',
			    ext2: 'uniTuikitExternal',
			    ext3: `${SDKAppID}`,
			})
			// #endif
			// #ifdef MP-WEIXIN  
			uni.$aegis.reportEvent({
			    name: 'platform',
			    ext1: 'platform-MP-WEIXIN',
			    ext2: 'uniTuikitExternal',
			    ext3: `${SDKAppID}`,
			})
			// #endif
			// #ifdef H5
			uni.$aegis.reportEvent({
			    name: 'platform',
			    ext1: 'platform-H5',
			    ext2: 'uniTuikitExternal',
			    ext3: `${SDKAppID}`,
			})
			uni.showToast({
				title: 'TUIKit 暂不支持 H5 / web ，请使用者自己完成兼容哦～ ',
				icon: 'none',
				duration: 3000
			});
			// #endif
			app.globalData.userInfo = {
				userSig,
				userID
			};
			setTokenStorage({
				userInfo: app.globalData.userInfo
			});
			wx.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true);
			uni.$TUIKit.login({
				userID: userID,
				userSig: userSig
			}).then(() => {
				uni.$aegis.reportEvent({
				    name: 'login',
				    ext1: 'login-success',
				    ext2: 'uniTuikitExternal',
				    ext3: `${SDKAppID}`,
				})
				console.log('im登录')
			}).catch((error) => {
				uni.$aegis.reportEvent({
				    name: 'login',
				    ext1: `login-failed#error:${error}`,
				    ext2: 'uniTuikitExternal',
				    ext3: `${SDKAppID}`,
				})
			})
			
			// 登录原生插件
			// #ifdef APP-PLUS
			if(typeof(uni.$TUICalling) == 'undefined') {
				uni.showToast({
					title: '如果需要音视频功能，请集成插件使用真机运行并且自定义基座调试哦～',
					icon: 'none',
					duration: 3000
				});
				logger.error('请使用真机运行并且自定义基座调试，否则影响音视频功能～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use');
			} else {
				uni.$TUICalling.login(
					{
						sdkAppID: SDKAppID,
						userID: userID,
						userSig: userSig
					},
					res => {
						console.log(JSON.stringify(res.msg));
						uni.showToast({
							title: 'login',
							icon: 'none'
						});
					}
				);
			}
			
			// #endif
			
			//登录成功后调转页面
			uni.navigateTo({
				url: '../TUI-Index/index'
			});
		}
			
	}
};
</script>

<style>
/* 微信授权 */

.wx-auth {
	height: calc(100vh);
	width: 100%;
}

.header {
	margin: 50upx 0 50upx 0;
	border-bottom: 1px solid #eee;
	text-align: center;
	width: 100%;
	height: 300rpx;
	line-height: 450rpx;
}

.header image {
	width: 200upx;
	height: 200upx;
}

.content2 {
	padding: 30upx 80upx;
}

.content2 text {
	display: block;
	color: #9d9d9d;
	margin-top: 40rpx;
}

.bottom {
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	    
}

.auth {
	border-radius: 15rpx;
	margin: 70rpx 50rpx 50rpx 50rpx;
	font-size: 35rpx;
	width: 60%;
	background: #8EC7F9;
	color: #ffffff;
	height: 60rpx;
	line-height: 60rpx;
}

.cancel-login {
	border-radius: 15rpx;
	margin: 70rpx 20rpx 50rpx 50rpx;
	font-size: 35rpx;
	background-color: #eeeeee;
	width: 30%;
	height: 60rpx;
	line-height: 60rpx;
}

.phone-login {
	width: 100%;
	justify-content: center;
}

.phone-login-text {
	color: #666666;
	border-bottom: #999999 solid 2upx;
}
</style>
